<?php
require_once '.config.inc.php';

class ListOrders
{

    public static function getData($auth, $NextToken = false)
    {
        $serviceUrl = "https://mws.amazonservices.com/Orders/2013-09-01";
        $serviceUrl_jp = "https://mws.amazonservices.jp/Orders/2013-09-01";
        $serviceUrl_eu = "https://mws-eu.amazonservices.com/Orders/2013-09-01";

        $config = array(
            'ServiceURL' => $serviceUrl,
            'ProxyHost' => null,
            'ProxyPort' => -1,
            'ProxyUsername' => null,
            'ProxyPassword' => null,
            'MaxErrorRetry' => 3,
        );

        $service = new MarketplaceWebServiceOrders_Client(
            $auth['AWS_ACCESS_KEY_ID'],
            $auth['AWS_SECRET_ACCESS_KEY'],
            APPLICATION_NAME,
            APPLICATION_VERSION,
            $config);
        if ($NextToken != false && $NextToken != null && $NextToken != '') {
            $request = new MarketplaceWebServiceOrders_Model_ListOrdersByNextTokenRequest();
            var_dump('MarketplaceWebServiceOrders_Model_ListOrdersByNextTokenRequest');
        } else {
            $request = new MarketplaceWebServiceOrders_Model_ListOrdersRequest();
        }
//        $file = fopen("ListOrders.txt", "a");
//        fwrite($file, $NextToken);
//        fclose($file);
        var_dump('NextToken:');
        var_dump($NextToken);
        $request->setSellerId($auth['MERCHANT_ID']);
        $request->setMWSAuthToken($auth['MWSAuthToken']);

        if ($NextToken != false && $NextToken != null && $NextToken != '') {
            $request->setNextToken($NextToken);
        } else {
            //$marketplaceIdList = new MarketplaceWebServiceOrders_Model_MarketplaceIdList();
            //$marketplaceIdList->setId(array('ATVPDKIKX0DER', 'A1PA6795UKMFR9', 'A1F83G8C2ARO7P'));  //ATVPDKIKX0DER：美國   A1PA6795UKMFR9：德國   A1F83G8C2ARO7P：英國
            //  $orderStatusList = new MarketplaceWebServiceOrders_Model_PaymentMethodList();
            //  $orderStatusList->setMethod(array('Unshipped','PartiallyShipped','Shipped'));

            $request->setMarketplaceId(array('ATVPDKIKX0DER', 'A1PA6795UKMFR9', 'A1F83G8C2ARO7P'));
            $request->setLastUpdatedAfter("2013-08-01T18:12:21");
            $request->setMaxResultsPerPage(100);
        }

        try {

            if ($NextToken != false && $NextToken != null && $NextToken != '') {
                $response = $service->ListOrdersByNextToken($request);
            } else {
                $response = $service->ListOrders($request);

            }

            $dom = new DOMDocument();
            $dom->loadXML($response->toXML());
            $dom->preserveWhiteSpace = false;
            $dom->formatOutput = true;
            // echo("ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
            $data = $dom->saveXML();
            $xml = simplexml_load_string($data);
            $data1 = json_decode(json_encode($xml), TRUE);
//            $file = fopen("ListOrders.txt", "a");
//            fwrite($file, print_r($data1, true));
//            fclose($file);
            return $data1;

        } catch (MarketplaceWebServiceOrders_Exception $ex) {
            echo("Caught Exception: " . $ex->getMessage() . "\n");
            echo("Response Status Code: " . $ex->getStatusCode() . "\n");
            echo("Error Code: " . $ex->getErrorCode() . "\n");
            echo("Error Type: " . $ex->getErrorType() . "\n");
            echo("Request ID: " . $ex->getRequestId() . "\n");
            echo("XML: " . $ex->getXML() . "\n");
            echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
        }

    }

    /**
     * 获取订单的商品
     * @param $auth
     * @param $orderId
     */
    public static function getDataItem($auth, $orderId)
    {

        $serviceUrl = "https://mws.amazonservices.com/Orders/2013-09-01";
        $serviceUrl_jp = "https://mws.amazonservices.jp/Orders/2013-09-01";
        $serviceUrl_eu = "https://mws-eu.amazonservices.com/Orders/2013-09-01";
        $config = array(
            'ServiceURL' => $serviceUrl,
            'ProxyHost' => null,
            'ProxyPort' => -1,
            'ProxyUsername' => null,
            'ProxyPassword' => null,
            'MaxErrorRetry' => 3,
        );
        $service = new MarketplaceWebServiceOrders_Client(
            $auth['AWS_ACCESS_KEY_ID'],
            $auth['AWS_SECRET_ACCESS_KEY'],
            APPLICATION_NAME,
            APPLICATION_VERSION,
            $config);
        $request = new MarketplaceWebServiceOrders_Model_ListOrderItemsRequest();
        $request->setSellerId($auth['MERCHANT_ID']);
        $request->setAmazonOrderId($orderId);
        $request->setMWSAuthToken($auth['MWSAuthToken']);
        try {
            $response = $service->ListOrderItems($request);

            $dom = new DOMDocument();
            $dom->loadXML($response->toXML());
            $dom->preserveWhiteSpace = false;
            $dom->formatOutput = true;
            // echo("ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
            $data = $dom->saveXML();
            $xml = simplexml_load_string($data);
            $data1 = json_decode(json_encode($xml), TRUE);
//            $file = fopen("OrderItems.txt", "a");
//            fwrite($file, print_r($data1, true));
//            fclose($file);
            return $data1;

        } catch (MarketplaceWebServiceOrders_Exception $ex) {
            echo("Caught Exception: " . $ex->getMessage() . "\n");
            echo("Response Status Code: " . $ex->getStatusCode() . "\n");
            echo("Error Code: " . $ex->getErrorCode() . "\n");
            echo("Error Type: " . $ex->getErrorType() . "\n");
            echo("Request ID: " . $ex->getRequestId() . "\n");
            echo("XML: " . $ex->getXML() . "\n");
            echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
        }

    }


    /**
     * 添加数据
     */
    public static function addData($result, $pdo, $auth, $token = false)
    {
        if ($token == false) {
            $ListOrdersResult = 'ListOrdersResult';
        } else {
            $ListOrdersResult = 'ListOrdersByNextTokenResult';
        }
        if (isset($result[$ListOrdersResult]['Orders'])) {
            foreach ($result[$ListOrdersResult]['Orders']['Order'] as $item) {
                $selectid = "select * from amazon_order where amazon_order_id=?";
                $getid = $pdo->prepare($selectid);
                $getid->execute([$item['AmazonOrderId']]);
                $hasOrder = $getid->fetchAll();
                $mapField = self::mapField();

                if (empty($hasOrder)) {  //添加
                    $orderId = $item['AmazonOrderId'];
                    $add = array();
                    foreach ($item as $field => $val) {
                        if (isset($mapField[$field])) {
                            $add[$mapField[$field]] = $val;
                        }
                        if (isset($item['ShippingAddress'])) {
                            $ShippingAddress = $item['ShippingAddress'];
                            foreach ($ShippingAddress as $keyShipee => $itemShip) {
                                if (isset($mapField[$keyShipee])) {
                                    $add[$mapField[$keyShipee]] = $itemShip;
                                }
                            }
                        }
                        if (isset($item['OrderTotal']['Amount'])) {
                            $add['amount'] = $item['OrderTotal']['Amount'];
                        }
                        if (isset($item['OrderTotal']['CurrencyCode'])) {
                            $add['currency_code'] = $item['OrderTotal']['CurrencyCode'];
                        }
                    }


                    foreach($add as $key=>$value){
                        $value = self::dealObjectData($value);
                        $add[$key]=$value;
                    }
                      var_dump($add);

                    $sql = "insert into   `amazon_order`  (";
                    $fieldLIst = array_keys($add);
                    $sql = $sql . implode(',', $fieldLIst);
                    $sql = $sql . ') values (';
                    for ($i = 1; $i <= count($fieldLIst); $i++) {
                        if ($i == count($fieldLIst)) {
                            $sql .= '?';
                        } else {
                            $sql .= '?,';
                        }
                    }
                    $sql .= ")";
                    $preObj2 = $pdo->prepare($sql);
                    $str2 = $preObj2->execute(array_values($add));
                    if ($str2) {
                        echo 'insert amazon_order success___', PHP_EOL;
                    } else {
                        echo 'insert amazon_order fail___', PHP_EOL;
                    }
                    $addOrderId = $pdo->lastInsertId();
                } else {  //修改
                    $needUpdate = 0;
                    $change = array();
                    $item['PurchaseDate'] = substr($item['PurchaseDate'], 0, 19);
                    $item['LastUpdateDate'] = substr($item['LastUpdateDate'], 0, 19);
                    $item['EarliestShipDate'] = substr($item['EarliestShipDate'], 0, 19);
                    $item['LatestShipDate'] = substr($item['LatestShipDate'], 0, 19);
                    $item['PurchaseDate'] = str_replace("T", " ", $item['PurchaseDate']);
                    $item['PurchaseDate'] = str_replace("Z", " ", $item['PurchaseDate']);
                    $item['LastUpdateDate'] = str_replace("T", " ", $item['LastUpdateDate']);
                    $item['LastUpdateDate'] = str_replace("Z", " ", $item['LastUpdateDate']);
                    $item['EarliestShipDate'] = str_replace("T", " ", $item['EarliestShipDate']);
                    $item['EarliestShipDate'] = str_replace("Z", " ", $item['EarliestShipDate']);
                    $item['LatestShipDate'] = str_replace("T", " ", $item['LatestShipDate']);
                    $item['LatestShipDate'] = str_replace("Z", " ", $item['LatestShipDate']);
                    foreach ($mapField as $fieldApiOrder => $fieldTable) {

                        if (isset($hasOrder[0][$fieldTable]) && isset($item[$fieldApiOrder])) {
                            $item[$fieldApiOrder] = self::dealObjectData($item[$fieldApiOrder]);
                            if ($hasOrder[0][$fieldTable] != $item[$fieldApiOrder]) {
                                echo $fieldApiOrder . " --- " . $hasOrder[0][$fieldTable] . " --- " . $item[$fieldApiOrder] . " need  update", PHP_EOL;
                                echo "<br>";
                                $needUpdate = 1;
                                $item[$fieldApiOrder] = str_replace("'", "\'", $item[$fieldApiOrder]);
                                $change[] = "`$fieldTable`='" . $item[$fieldApiOrder] . "'";
                            }
                        }

                    }
                    if (isset($item['ShippingAddress'])) {
                        $ShippingAddress = $item['ShippingAddress'];
                        foreach ($ShippingAddress as $keyShipee => $itemShip) {
                            if (isset($mapField[$keyShipee]) && isset($hasOrder[0][$mapField[$keyShipee]])) {
                                $itemShip = $itemShip;
                                if ($hasOrder[0][$mapField[$keyShipee]] != $itemShip) {
                                    echo " ShippingAddress " . $keyShipee . " --- " . $hasOrder[0][$mapField[$keyShipee]] . " --- " . $itemShip . " need  update", PHP_EOL;
                                    echo "<br>";
                                    $needUpdate = 1;
                                    $itemShip = str_replace("'", "\'", $itemShip);
                                    $change[] = "`$mapField[$keyShipee]`='" . $itemShip . "'";
                                }
                            }
                        }
                    }
                    if (isset($item['OrderTotal']['Amount']) && isset($hasOrder[0]['amount']) && $hasOrder[0]['amount'] != $item['OrderTotal']['Amount']) {
                        echo " Amount   --- " . $hasOrder[0]['amount'] . " --- " . $item['OrderTotal']['Amount'] . " need  update", PHP_EOL;
                        echo "<br>";
                        $needUpdate = 1;
                        $change[] = "`amount`='" . $item['OrderTotal']['Amount'] . "'";
                    }
                    if (isset($item['OrderTotal']['CurrencyCode']) && isset($hasOrder[0]['currency_code']) && $hasOrder[0]['currency_code'] != $item['OrderTotal']['CurrencyCode']) {
                        echo " CurrencyCode   --- " . $hasOrder[0]['currency_code'] . " --- " . $item['OrderTotal']['CurrencyCode'] . " need  update", PHP_EOL;
                        echo "<br>";
                        $needUpdate = 1;
                        $change[] = "`currency_code`='" . $item['OrderTotal']['CurrencyCode'] . "'";
                    }

                    if ($needUpdate == 1) {
                        $sql = " update  amazon_order  set  ";
                        $sql = $sql . implode(",", $change);
                        $sql = $sql . " where id=" . $hasOrder[0]['id'];
                        $countUpdate = $pdo->exec($sql);
                        if ($countUpdate > 0) {
                            echo 'update amazon_order success___', PHP_EOL;
                        } else {
                            echo 'update amazon_order fail___', PHP_EOL;
                            echo $sql, PHP_EOL;
                        }
                    }
                    $addOrderId = $hasOrder[0]['id'];
                    $orderId = $hasOrder[0]['amazon_order_id'];
                }

                if ($addOrderId > 0 && isset($orderId) && $orderId != null && $orderId != '') {
                  //  var_dump($addOrderId);
                    $mapItemField = self::mapItemField();
                    $itemResult = self::getDataItem($auth, $orderId);
                    if (isset($itemResult['ListOrderItemsResult']['OrderItems']['OrderItem']['OrderItemId'])) {
                        $OrderItem = $itemResult['ListOrderItemsResult']['OrderItems']['OrderItem'];
                        $selectid = "select * from amazon_order_item where amazon_order_id=$addOrderId  and   `order_item_id`=? and 	seller_sku=? and asin=?    ";
                        $getid = $pdo->prepare($selectid);
                        $getid->execute([$OrderItem['OrderItemId'], $OrderItem['SellerSKU'], $OrderItem['ASIN']]);
                        $hasOrderItem = $getid->fetchAll();

                        if (empty($hasOrderItem)) {  //添加

                            $addItem = array();
                            foreach ($OrderItem as $keyOrderItem => $valOrderItem) {
                                if (isset($mapItemField[$keyOrderItem])) {
                                    $addItem[$mapItemField[$keyOrderItem]] = $valOrderItem;
                                }
                            }
                            if (isset($OrderItem['ItemPrice']['Amount'])) {
                                $addItem['amount'] = $OrderItem['ItemPrice']['Amount'];
                            }
                            if (isset($OrderItem['ItemPrice']['CurrencyCode'])) {
                                $addItem['currency_code'] = $OrderItem['ItemPrice']['CurrencyCode'];
                            }
                            if (isset($OrderItem['ItemTax']['Amount'])) {
                                $addItem['item_tax'] = $OrderItem['ItemTax']['Amount'];
                            }
                            if (isset($OrderItem['PromotionDiscount']['Amount'])) {
                                $addItem['promotion_discount'] = $OrderItem['PromotionDiscount']['Amount'];
                            }
                            if (isset($OrderItem['PromotionIds']['PromotionId'])) {
                                $OrderItem['PromotionIds']['PromotionId']=self::dealObjectData($OrderItem['PromotionIds']['PromotionId']);
                                $addItem['promotionid'] = $OrderItem['PromotionIds']['PromotionId'];
                            }
                            if (isset($OrderItem['ShippingDiscount']['Amount'])) {
                                $addItem['shipping_discount'] = $OrderItem['ShippingDiscount']['Amount'];
                            }

                            if (!empty($addItem)) {
                                foreach ($addItem as &$valOri) {
                                    $valOri = self::dealObjectData($valOri);
                                }
                                $addItem['amazon_order_id'] = $addOrderId;
                                $sql = "insert into   `amazon_order_item`  (";
                                $fieldLIst = array_keys($addItem);
                                $sql = $sql . implode(',', $fieldLIst);
                                $sql = $sql . ') values (';
                                for ($i = 1; $i <= count($fieldLIst); $i++) {
                                    if ($i == count($fieldLIst)) {
                                        $sql .= '?';
                                    } else {
                                        $sql .= '?,';
                                    }
                                }
                                $sql .= ")";
                                $preObj2 = $pdo->prepare($sql);
                                $str2 = $preObj2->execute(array_values($addItem));
                                if ($str2) {
                                    echo 'insert amazon_order_item success___', PHP_EOL;

                                } else {
                                    echo 'insert amazon_order_item fail___', PHP_EOL;
                                }
                            }
                        } else {  //修改

                            $needUpdate = 0;
                            $change = array();
                           //  var_dump('11111111');
                            foreach ($mapItemField as $fieldApi => $fieldTable) {
                             //   var_dump($fieldApi);
                              //  var_dump($fieldTable);
                                if (isset($hasOrderItem[0][$fieldTable]) && isset($OrderItem[$fieldApi])) {
                                  //  var_dump($hasOrderItem[0][$fieldTable]);
                                //    var_dump($OrderItem[$fieldApi]);
                                    $OrderItem[$fieldApi] = self::dealObjectData($OrderItem[$fieldApi]);

                                    if ($hasOrderItem[0][$fieldTable] != $OrderItem[$fieldApi]) {
                                        echo $fieldApi . " --- " . $hasOrderItem[0][$fieldTable] . " --- " . $OrderItem[$fieldApi] . " need  update", PHP_EOL;
                                        echo "<br>";
                                        $needUpdate = 1;
                                        $item[$fieldApi] = str_replace("'", "\'", $item[$fieldApi]);
                                        $change[] = "`$fieldTable`='" . $item[$fieldApi] . "'";
                                    }
                                }
                            }

                            if (isset($OrderItem['ItemPrice']['Amount']) && $hasOrderItem[0]['amount'] != $OrderItem['ItemPrice']['Amount']) {
                                $needUpdate = 1;
                                $change[] = "`amount`='" . $OrderItem['ItemPrice']['Amount'] . "'";
                            }
                            if (isset($OrderItem['ItemPrice']['CurrencyCode']) && $hasOrderItem[0]['currency_code'] != $OrderItem['ItemPrice']['CurrencyCode']) {
                                $needUpdate = 1;
                                $change[] = "`currency_code`='" . $OrderItem['ItemPrice']['CurrencyCode'] . "'";
                            }
                            if (isset($OrderItem['ItemTax']['Amount']) && $hasOrderItem[0]['item_tax'] != $OrderItem['ItemTax']['Amount']) {
                                $needUpdate = 1;
                                $change[] = "`item_tax`='" . $OrderItem['ItemTax']['Amount'] . "'";
                            }
                            if (isset($OrderItem['PromotionDiscount']['Amount']) && $hasOrderItem[0]['promotion_discount'] != $OrderItem['PromotionDiscount']['Amount']) {
                                $needUpdate = 1;
                                $change[] = "`promotion_discount`='" . $OrderItem['PromotionDiscount']['Amount'] . "'";
                            }
                            if (isset($OrderItem['PromotionIds']['PromotionId']) && $hasOrderItem[0]['promotionid'] != $OrderItem['PromotionIds']['PromotionId']) {
                                $needUpdate = 1;
                                $OrderItem['PromotionIds']['PromotionId']=self::dealObjectData($OrderItem['PromotionIds']['PromotionId']);
                                $change[] = "`promotionid`='" . $OrderItem['PromotionIds']['PromotionId'] . "'";
                            }
                            if (isset($OrderItem['ShippingDiscount']['Amount']) && $hasOrderItem[0]['shipping_discount'] != $OrderItem['ShippingDiscount']['Amount']) {
                                $needUpdate = 1;
                                $change[] = "`shipping_discount`='" . $OrderItem['ShippingDiscount']['Amount'] . "'";
                            }
                         //   var_dump($change);
                            if ($needUpdate == 1) {

                                $sql = " update  amazon_order_item  set  ";
                                $sql = $sql . implode(",", $change);
                                $sql = $sql . " where id=" . $hasOrder[0]['id'];
                                echo $sql, PHP_EOL;
                                $countUpdate = $pdo->exec($sql);
                                if ($countUpdate > 0) {
                                    echo 'update amazon_order_item success___', PHP_EOL;
                                } else {
                                    echo 'update amazon_order_item fail___', PHP_EOL;
                                    echo $sql, PHP_EOL;
                                }

                            }

                        }
                    } else {
                        if (isset($itemResult['ListOrderItemsResult']['OrderItems']['OrderItem'][0]['OrderItemId'])) {
                            $OrderItemList = $itemResult['ListOrderItemsResult']['OrderItems']['OrderItem'];
                            foreach ($OrderItemList as $OrderItem) {

                                $mapItemField = self::mapItemField();

                                $selectid = "select * from amazon_order_item where amazon_order_id=$addOrderId  and   `order_item_id`=? and 	seller_sku=? and asin=?    ";
                                $getid = $pdo->prepare($selectid);
                                $getid->execute([$OrderItem['OrderItemId'], $OrderItem['SellerSKU'], $OrderItem['ASIN']]);
                                $hasOrderItem = $getid->fetchAll();
                                if (empty($hasOrderItem)) {  //添加

                                    $addItem = array();
                                    foreach ($OrderItem as $keyOrderItem => $valOrderItem) {
                                        if (isset($mapItemField[$keyOrderItem])) {
                                            $addItem[$mapItemField[$keyOrderItem]] = $valOrderItem;
                                        }
                                    }
                                    if (isset($OrderItem['ItemPrice']['Amount'])) {
                                        $addItem['amount'] = $OrderItem['ItemPrice']['Amount'];
                                    }
                                    if (isset($OrderItem['ItemPrice']['CurrencyCode'])) {
                                        $addItem['currency_code'] = $OrderItem['ItemPrice']['CurrencyCode'];
                                    }
                                    if (isset($OrderItem['ItemTax']['Amount'])) {
                                        $addItem['item_tax'] = $OrderItem['ItemTax']['Amount'];
                                    }
                                    if (isset($OrderItem['PromotionDiscount']['Amount'])) {
                                        $addItem['promotion_discount'] = $OrderItem['PromotionDiscount']['Amount'];
                                    }
                                    if (isset($OrderItem['PromotionIds']['PromotionId'])) {
                                        $OrderItem['PromotionIds']['PromotionId']=self::dealObjectData($OrderItem['PromotionIds']['PromotionId']);
                                        $addItem['promotionid'] = $OrderItem['PromotionIds']['PromotionId'];
                                    }
                                    if (isset($OrderItem['ShippingDiscount']['Amount'])) {
                                        $addItem['shipping_discount'] = $OrderItem['ShippingDiscount']['Amount'];
                                    }
                                    if (!empty($addItem)) {
                                        foreach ($addItem as &$valOri) {
                                            $valOri = self::dealObjectData($valOri);
                                        }
                                        $addItem['amazon_order_id'] = $addOrderId;
                                        $sql = "insert into   `amazon_order_item`  (";
                                        $fieldLIst = array_keys($addItem);
                                        $sql = $sql . implode(',', $fieldLIst);
                                        $sql = $sql . ') values (';
                                        for ($i = 1; $i <= count($fieldLIst); $i++) {
                                            if ($i == count($fieldLIst)) {
                                                $sql .= '?';
                                            } else {
                                                $sql .= '?,';
                                            }
                                        }
                                        $sql .= ")";
                                        $preObj2 = $pdo->prepare($sql);
                                        $str2 = $preObj2->execute(array_values($addItem));
                                        if ($str2) {
                                            echo 'insert amazon_order_item success___', PHP_EOL;
                                        } else {
                                            echo 'insert amazon_order_item fail___', PHP_EOL;
                                        }
                                    }
                                }else{
                                   // var_dump('2222222');
                                    $needUpdate = 0;
                                    $change = array();

                                    foreach ($mapItemField as $fieldApi => $fieldTable) {
                                        //var_dump($fieldApi);
                                        //var_dump($fieldTable);
                                        if (isset($hasOrderItem[0][$fieldTable]) && isset($OrderItem[$fieldApi])) {
                                         //   var_dump($hasOrderItem[0][$fieldTable]);
                                         //   var_dump($OrderItem[$fieldApi]);
                                            $OrderItem[$fieldApi] = self::dealObjectData($OrderItem[$fieldApi]);


                                            if ($hasOrderItem[0][$fieldTable] != $OrderItem[$fieldApi]) {
                                                echo $fieldApi . " --- " . $hasOrderItem[0][$fieldTable] . " --- " . $OrderItem[$fieldApi] . " need  update", PHP_EOL;
                                                echo "<br>";
                                                $needUpdate = 1;
                                                $item[$fieldApi] = str_replace("'", "\'", $item[$fieldApi]);
                                                $change[] = "`$fieldTable`='" . $item[$fieldApi] . "'";
                                            }
                                        }
                                    }

                                    if (isset($OrderItem['ItemPrice']['Amount']) && $hasOrderItem[0]['amount'] != $OrderItem['ItemPrice']['Amount']) {
                                        $needUpdate = 1;
                                        $change[] = "`amount`='" . $OrderItem['ItemPrice']['Amount'] . "'";
                                    }
                                    if (isset($OrderItem['ItemPrice']['CurrencyCode']) && $hasOrderItem[0]['currency_code'] != $OrderItem['ItemPrice']['CurrencyCode']) {
                                        $needUpdate = 1;
                                        $change[] = "`currency_code`='" . $OrderItem['ItemPrice']['CurrencyCode'] . "'";
                                    }
                                    if (isset($OrderItem['ItemTax']['Amount']) && $hasOrderItem[0]['item_tax'] != $OrderItem['ItemTax']['Amount']) {
                                        $needUpdate = 1;
                                        $change[] = "`item_tax`='" . $OrderItem['ItemTax']['Amount'] . "'";
                                    }
                                    if (isset($OrderItem['PromotionDiscount']['Amount']) && $hasOrderItem[0]['promotion_discount'] != $OrderItem['PromotionDiscount']['Amount']) {
                                        $needUpdate = 1;
                                        $change[] = "`promotion_discount`='" . $OrderItem['PromotionDiscount']['Amount'] . "'";
                                    }
                                    if (isset($OrderItem['PromotionIds']['PromotionId']) && $hasOrderItem[0]['promotionid'] != $OrderItem['PromotionIds']['PromotionId']) {
                                        $needUpdate = 1;
                                        $OrderItem['PromotionIds']['PromotionId']=self::dealObjectData($OrderItem['PromotionIds']['PromotionId']);
                                        $change[] = "`promotionid`='" . $OrderItem['PromotionIds']['PromotionId'] . "'";
                                    }
                                    if (isset($OrderItem['ShippingDiscount']['Amount']) && $hasOrderItem[0]['shipping_discount'] != $OrderItem['ShippingDiscount']['Amount']) {
                                        $needUpdate = 1;
                                        $change[] = "`shipping_discount`='" . $OrderItem['ShippingDiscount']['Amount'] . "'";
                                    }
                                  //  var_dump($change);
                                    if ($needUpdate == 1) {

                                        $sql = " update  amazon_order_item  set  ";
                                        $sql = $sql . implode(",", $change);
                                        $sql = $sql . " where id=" . $hasOrder[0]['id'];
                                        echo $sql, PHP_EOL;
                                        $countUpdate = $pdo->exec($sql);
                                        if ($countUpdate > 0) {
                                            echo 'update amazon_order_item success___', PHP_EOL;
                                        } else {
                                            echo 'update amazon_order_item fail___', PHP_EOL;
                                            echo $sql, PHP_EOL;
                                        }

                                    }
                                }
                            }

                        } else {
                            echo 'amazon  api  orderItems no data ', PHP_EOL;
                        }
                    }
                }
            }
        }
    }


    /**
     * 字段映射
     */
    public static function mapField()
    {
        $array = array(
            'AmazonOrderId' => 'amazon_order_id',
            'SellerOrderId' => 'seller_order_id',
            'PurchaseDate' => 'purchase_date',
            'LastUpdateDate' => 'last_update_date',
            'OrderStatus' => 'order_status',
            'FulfillmentChannel' => 'fulfillment_channel',
            'SalesChannel' => 'sales_channel',
            'ShipServiceLevel' => 'ship_service_level',
            //   'ShippingAddress' => 'shipping_address',
            'City' => 'city',
            'StateOrRegion' => 'state_or_region',
            'PostalCode' => 'postal_code',
            'CountryCode' => 'country_code',
            'CurrencyCode' => 'currency_code',
            'Amount' => 'amount',
            'NumberOfItemsShipped' => 'number_of_items_shipped',
            'NumberOfItemsUnshipped' => 'number_of_items_unshipped',
            'PaymentExecutionDetail' => 'payment_execution_detail',
            'PaymentMethod' => 'payment_method',
            'PaymentMethodDetails' => 'payment_method_details',
            'MarketplaceId' => 'marketplace_id',
            'BuyerEmail' => 'buyer_email',
            'ShipmentServiceLevelCategory' => 'shipment_service_level_category',
            'OrderType' => 'order_type',
            'EarliestShipDate' => 'earliest_ship_date',
            'LatestShipDate' => 'latest_ship_date',
            'IsBusinessOrder' => 'is_business_order',
            'IsPrime' => 'is_prime',
            'IsPremiumOrder' => 'is_premium_order',
            'IsReplacementOrder' => 'is_replacement_order',
        );
        return $array;
    }

    /**
     *
     */
    public static function mapItemField()
    {
        $array = array(
            'ASIN' => 'asin',
            'SellerSKU' => 'seller_sku',
            'OrderItemId' => 'order_item_id',
            'Title' => 'title',
            'QuantityOrdered' => 'quantity_ordered',
            'QuantityShipped' => 'quantity_shipped',
            'ConditionId' => 'condition_id',
            'ConditionSubtypeId' => 'condition_subtype_id',
        );
        return $array;
    }


    public static function dealObjectData($val)
    {
        if (is_int($val)) {
            return $val;
        }
        if (is_string($val)) {
            return $val;
        }
        if (is_array($val)) {
            if (empty($val)) {
                return '';
            } else {
                $val = json_encode($val);
                return $val;
            }
        }
        if (is_object($val)) {
            if (empty($val)) {
                return '';
            } else {
                $val = json_encode($val);
                return $val;
            }
        }
    }

}